// 🚀 PWA注册脚本 - 精英杂志
// 功能：注册Service Worker，处理安装提示

// 📱 检查浏览器支持
if ('serviceWorker' in navigator) {
  // 等待页面加载完成
  window.addEventListener('load', () => {
    registerServiceWorker();
  });
}

// 🔄 注册Service Worker
function registerServiceWorker() {
  navigator.serviceWorker.register('/service-worker.js')
    .then(registration => {
      console.log('✅ Service Worker 注册成功:', registration);
      
      // 监听更新
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing;
        newWorker.addEventListener('statechange', () => {
          if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
            // 发现新版本
            showUpdateNotification();
          }
        });
      });

      // 定期检查更新（每小时）
      setInterval(() => {
        registration.update();
      }, 60 * 60 * 1000);

    })
    .catch(error => {
      console.log('❌ Service Worker 注册失败:', error);
    });
}

// 📲 处理安装提示
let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  // 防止Chrome自动显示安装提示
  e.preventDefault();
  
  // 保存事件以便后续使用
  deferredPrompt = e;
  
  // 显示自定义安装按钮
  showInstallButton();
  
  console.log('📲 安装提示已捕获');
});

// 🎯 显示安装按钮
function showInstallButton() {
  // 创建安装按钮
  const installButton = document.createElement('div');
  installButton.id = 'pwa-install-button';
  installButton.innerHTML = `
    <div style="
      position: fixed;
      bottom: 20px;
      right: 20px;
      background: #1e3a8f;
      color: white;
      padding: 12px 20px;
      border-radius: 25px;
      cursor: pointer;
      box-shadow: 0 4px 12px rgba(0,0,0,0.3);
      z-index: 9999;
      font-size: 14px;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 8px;
      transition: all 0.3s ease;
    " onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
      📱 安装应用
    </div>
  `;
  
  document.body.appendChild(installButton);
  
  // 添加点击事件
  installButton.addEventListener('click', installApp);
}

// 📲 触发安装
function installApp() {
  if (!deferredPrompt) {
    console.log('❌ 安装提示不可用');
    return;
  }
  
  // 显示安装提示
  deferredPrompt.prompt();
  
  // 等待用户选择
  deferredPrompt.userChoice.then((choiceResult) => {
    if (choiceResult.outcome === 'accepted') {
      console.log('✅ 用户接受了安装');
      // 隐藏安装按钮
      const installButton = document.getElementById('pwa-install-button');
      if (installButton) {
        installButton.style.display = 'none';
      }
    } else {
      console.log('❌ 用户拒绝了安装');
    }
    
    deferredPrompt = null;
  });
}

// 🔄 显示更新通知
function showUpdateNotification() {
  const updateNotification = document.createElement('div');
  updateNotification.id = 'pwa-update-notification';
  updateNotification.innerHTML = `
    <div style="
      position: fixed;
      top: 20px;
      right: 20px;
      background: #10b981;
      color: white;
      padding: 15px 20px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.3);
      z-index: 9999;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;
      max-width: 300px;
    ">
      <span>🔄 发现新版本</span>
      <button onclick="window.location.reload()" style="
        background: white;
        color: #10b981;
        border: none;
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        font-weight: 500;
      ">立即更新</button>
      <span onclick="this.parentElement.style.display='none'" style="
        cursor: pointer;
        margin-left: auto;
        font-size: 18px;
      ">×</span>
    </div>
  `;
  
  document.body.appendChild(updateNotification);
  
  // 5秒后自动隐藏
  setTimeout(() => {
    if (updateNotification) {
      updateNotification.style.display = 'none';
    }
  }, 5000);
}

// 📊 获取应用状态
function getAppStatus() {
  if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
    return {
      installed: true,
      controller: navigator.serviceWorker.controller.scriptURL,
      status: '已安装'
    };
  }
  return {
    installed: false,
    status: '未安装'
  };
}

// 🎯 手动更新
function forceUpdate() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistration().then(registration => {
      if (registration) {
        registration.update().then(() => {
          console.log('🔄 手动更新检查完成');
          window.location.reload();
        });
      }
    });
  }
}

// 🔔 请求通知权限
function requestNotificationPermission() {
  if ('Notification' in window) {
    Notification.requestPermission().then(permission => {
      console.log('🔔 通知权限:', permission);
      
      if (permission === 'granted') {
        // 订阅推送通知
        subscribeToPushNotifications();
      }
    });
  }
}

// 📲 订阅推送通知
async function subscribeToPushNotifications() {
  if ('serviceWorker' in navigator && 'PushManager' in window) {
    try {
      const registration = await navigator.serviceWorker.ready;
      const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('YOUR_PUBLIC_VAPID_KEY')
      });
      
      console.log('✅ 推送订阅成功:', subscription);
      
      // 发送订阅信息到服务器
      await fetch('/api/push/subscribe', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(subscription)
      });
      
    } catch (error) {
      console.log('❌ 推送订阅失败:', error);
    }
  }
}

// 🔑 VAPID密钥转换
function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');
  
  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);
  
  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

// 🎯 初始化PWA功能
function initializePWA() {
  console.log('🚀 初始化PWA功能...');
  
  // 检查是否已安装
  const status = getAppStatus();
  console.log('📱 PWA状态:', status);
  
  // 请求通知权限（可选）
  if (Math.random() > 0.7) { // 30%概率请求，避免打扰
    setTimeout(requestNotificationPermission, 3000);
  }
}

// 🚀 页面加载完成后初始化
window.addEventListener('load', initializePWA);